<template>
    <div class="sidebar">
        <div v-if="loading" class="menu-loading">
            <el-icon class="is-loading">
                <Loading />
            </el-icon>
            <span>加载菜单中...</span>
        </div>
        <el-menu
            v-else
            class="sidebar-el-menu"
            :default-active="onRoutes"
            :collapse="sidebar.collapse"
            :background-color="sidebar.bgColor"
            :text-color="sidebar.textColor"
            router
        >
            <template v-for="item in transformMenuData(menuData)" :key="item.id">
                <template v-if="item.children">
                    <el-sub-menu :index="item.index">
                        <template #title>
                            <el-icon>
                                <component :is="item.icon"></component>
                            </el-icon>
                            <span>{{ item.title }}</span>
                        </template>
                        <template v-for="subItem in item.children" :key="subItem.id">
                            <el-sub-menu
                                v-if="subItem.children"
                                :index="subItem.index"
                            >
                                <template #title>{{ subItem.title }}</template>
                                <el-menu-item
                                    v-for="threeItem in subItem.children"
                                    :key="threeItem.id"
                                    :index="threeItem.index"
                                >
                                    {{ threeItem.title }}
                                </el-menu-item>
                            </el-sub-menu>
                            <el-menu-item v-else :index="subItem.index">
                                {{ subItem.title }}
                            </el-menu-item>
                        </template>
                    </el-sub-menu>
                </template>
                <template v-else>
                    <el-menu-item :index="item.index">
                        <el-icon>
                            <component :is="item.icon"></component>
                        </el-icon>
                        <template #title>{{ item.title }}</template>
                    </el-menu-item>
                </template>
            </template>
        </el-menu>
    </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
import { useSidebarStore } from '../store/sidebar';
import { useRoute } from 'vue-router';
import { getMenuTree } from '@/api/system/menu';
import { MenuItem } from '@/types/menu';
import { ElMessage } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';
import { menuPermissionChecker } from '@/utils/menu-permission';

const route = useRoute();
const onRoutes = computed(() => {
    return route.path;
});

const sidebar = useSidebarStore();

// 菜单数据
const menuData = ref<MenuItem[]>([]);
const loading = ref(false);

// 转换菜单数据格式
const transformMenuData = (menus: MenuItem[]): any[] => {
    return menus
        .filter(menu => menu.isDisplay === 1 && menu.status === 1) // 只显示启用的菜单
        .map(menu => ({
            id: String(menu.id), // 确保ID是字符串类型
            index: menu.url,
            title: menu.menuName,
            icon: menu.icon || 'Menu',
            children: menu.children && menu.children.length > 0 
                ? transformMenuData(menu.children) 
                : undefined
        }));
};

// 获取菜单数据
const loadMenuData = async () => {
    try {
        loading.value = true;
        
        // 设置超时
        const timeoutPromise = new Promise((_, reject) => {
            setTimeout(() => reject(new Error('请求超时')), 10000);
        });
        
        const apiPromise = getMenuTree();
        const res = await Promise.race([apiPromise, timeoutPromise]);
        const responseData = res as any;

        console.log('菜单API响应:', responseData);

        if (responseData && responseData.code === 200 && responseData.data) {
            menuData.value = responseData.data;
            console.log('菜单数据加载成功:', menuData.value);
            
            // 更新权限检查器的菜单数据
            menuPermissionChecker.setMenuData(menuData.value);
        } else {
            const errorMsg = (responseData && responseData.msg) || '获取菜单数据失败';
            console.error('菜单API返回错误:', errorMsg);
            ElMessage.error(errorMsg);
            menuData.value = [];
        }
    } catch (error) {
        console.error('获取菜单数据失败:', error);
        ElMessage.error('获取菜单数据失败，请检查网络连接或联系管理员');
        
        // 使用备用静态菜单数据
        menuData.value = getFallbackMenuData();
        console.log('使用备用菜单数据:', menuData.value);
        
        // 更新权限检查器的菜单数据
        menuPermissionChecker.setMenuData(menuData.value);
    } finally {
        loading.value = false;
    }
};

// 备用菜单数据
const getFallbackMenuData = (): MenuItem[] => {
    return [
        {
            id: '1',
            parentId: '0',
            menuName: '系统首页',
            menuCode: 'dashboard',
            url: '/dashboard',
            sortOrder: 1,
            icon: 'House',
            isDisplay: 1,
            description: '系统首页',
            status: 1,
            createBy: 'system',
            createTime: new Date().toISOString(),
            updateBy: 'system',
            updateTime: new Date().toISOString(),
            children: [],
            checked: false
        },
        {
            id: '2',
            parentId: '0',
            menuName: '系统管理',
            menuCode: 'system',
            url: '/system',
            sortOrder: 2,
            icon: 'Setting',
            isDisplay: 1,
            description: '系统管理',
            status: 1,
            createBy: 'system',
            createTime: new Date().toISOString(),
            updateBy: 'system',
            updateTime: new Date().toISOString(),
            children: [
                {
                    id: '2-1',
                    parentId: '2',
                    menuName: '用户管理',
                    menuCode: 'system-user',
                    url: '/system-user',
                    sortOrder: 1,
                    icon: 'User',
                    isDisplay: 1,
                    description: '用户管理',
                    status: 1,
                    createBy: 'system',
                    createTime: new Date().toISOString(),
                    updateBy: 'system',
                    updateTime: new Date().toISOString(),
                    children: [],
                    checked: false
                },
                {
                    id: '2-2',
                    parentId: '2',
                    menuName: '菜单管理',
                    menuCode: 'system-menu',
                    url: '/system-menu',
                    sortOrder: 2,
                    icon: 'Menu',
                    isDisplay: 1,
                    description: '菜单管理',
                    status: 1,
                    createBy: 'system',
                    createTime: new Date().toISOString(),
                    updateBy: 'system',
                    updateTime: new Date().toISOString(),
                    children: [],
                    checked: false
                }
            ],
            checked: false
        },
        {
            id: '3',
            parentId: '0',
            menuName: '会员管理',
            menuCode: 'member',
            url: '/member',
            sortOrder: 3,
            icon: 'UserFilled',
            isDisplay: 1,
            description: '会员管理',
            status: 1,
            createBy: 'system',
            createTime: new Date().toISOString(),
            updateBy: 'system',
            updateTime: new Date().toISOString(),
            children: [
                {
                    id: '3-1',
                    parentId: '3',
                    menuName: '会员列表',
                    menuCode: 'member-list',
                    url: '/member-list',
                    sortOrder: 1,
                    icon: 'List',
                    isDisplay: 1,
                    description: '会员列表',
                    status: 1,
                    createBy: 'system',
                    createTime: new Date().toISOString(),
                    updateBy: 'system',
                    updateTime: new Date().toISOString(),
                    children: [],
                    checked: false
                }
            ],
            checked: false
        }
    ];
};

// 页面初始化
onMounted(() => {
    loadMenuData();
});
</script>

<style scoped>
.sidebar {
    display: block;
    position: absolute;
    left: 0;
    top: 70px;
    bottom: 0;
    overflow-y: scroll;
}

.sidebar::-webkit-scrollbar {
    width: 0;
}

.sidebar-el-menu:not(.el-menu--collapse) {
    width: 250px;
}

.sidebar-el-menu {
    min-height: 100%;
}

.menu-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: #909399;
    font-size: 14px;
}

.menu-loading .el-icon {
    font-size: 24px;
    margin-bottom: 10px;
}
</style>
